<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>发布/订阅模式</title>
</head>
<body>
    <script>
        // 事件触发器
        class EventEmitter{
            constructor(){
                // {'click': [fn1, fn2], 'handler': [fn1]}
                this.subs = []
            }
            // 注册事件
            $on(eventType, callback){
                this.subs[eventType] =this.subs[eventType] || []
                this.subs[eventType].push(callback)
            }
            //触发事件
            $emit(eventType){
                if(this.subs[eventType]){
                    this.subs[eventType].forEach(callback=> callback())
                }
            }
        }

        // 测试
        const event = new EventEmitter()
        event.$on('click',()=>{
            console.log('click')
        })
        event.$on('click',()=>{
            console.log('click1')
        })
        event.$emit('click')
    </script>
</body>
</html>